package su.samlib.informer.session.impl;

import su.samlib.informer.session.SessionHandler;
import su.samlib.informer.session.SessionManager;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Random;

public class SessionManagerImpl implements SessionManager {

    private class SessionGenerator {
        private static final String ALGORITHM = "MD5";
        private static final int RANDOMDATA_LENGTH = 512;
        private final Random randomGenerator = new Random();
        private MessageDigest messageDigest;


        private SessionGenerator() {
            try {
                messageDigest = MessageDigest.getInstance(ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        private byte[] generateRandomData() {
            byte[] data = new byte[RANDOMDATA_LENGTH];
            randomGenerator.nextBytes(data);
            return data;
        }

        private byte[] generateSessionAlgorithm() {
            byte[] input = generateRandomData();
            return messageDigest.digest(input);
        }

        private String generateSessionID() {
            StringBuilder sb = new StringBuilder();
            byte[] sessionKey = generateSessionAlgorithm();
            BigInteger sessionKeyBigInteger = new BigInteger(sessionKey);
            String output = sessionKeyBigInteger.abs().toString(16);
            sb.append(output);
            if (output.length() == 31) {
                sb.insert(0, "0");
            }
            return sb.toString();
        }
    }

    private final SessionGenerator sessionGenerator = new SessionGenerator();
    private final HashMap<String,SessionHandler> sessions = new HashMap<String, SessionHandler>();

    @Override
    public synchronized SessionHandler newSessionHandler() {
        final SessionHandler sh = new SessionHandlerImpl();
        String sessionID = sessionGenerator.generateSessionID();
        while(sessions.containsKey(sessionID)) {
            sessionID = sessionGenerator.generateSessionID();
        }
        sessions.put(sessionID,sh);
        return sh;
    }

    public synchronized boolean containsSession(String sessionID){
        return sessions.containsKey(sessionID);
    }


    @Override
    public boolean gc() {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
